package com.ityy.ruiji.controller;

import com.ityy.ruiji.common.R;
import com.ityy.ruiji.entity.Employee;
import com.ityy.ruiji.entity.Page;
import com.ityy.ruiji.service.RuiJiService;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/employee")
public class RuiJiController {

    @Autowired
    private RuiJiService ruiJiService;

    /**
     *   url；  http://localhost:8080/employee/login
     *   请求方式：POST
     *   请求参数：{
     * 				"username": "admin",
     *				"password": "123456"
     * 			}
     *   返回值：通过看前端代码我发现返回值必须包含三个属性：
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee , HttpSession httpSession){
        R<Employee> result = ruiJiService.login(employee);
        if (result.getCode()==1){
            Employee resultData = result.getData();
            httpSession.setAttribute("employee",resultData.getId());
        }
        return result;
    }

    @PostMapping("/logout")
    public R logout(HttpSession httpSession){
       httpSession.invalidate();
        return R.success("退出成功");
    }

    @PostMapping
    public R save(@RequestBody Employee employee, HttpSession session){
        Long employee1 = (Long) session.getAttribute("employee");
        employee.setCreateUser(employee1);
        employee.setUpdateUser(employee1);
        R save =  ruiJiService.save(employee);
        return save;
    }

    @GetMapping("page")
    //http://localhost:8080/employee/page?page=1&pageSize=10&name=.
    public R<Page> findByName(@RequestParam Integer page ,
                              @RequestParam Integer pageSize , String name){
        R<Page> r=ruiJiService.findByName(page,pageSize,name);
        return r;
    }

    @PutMapping
    public R update(@RequestBody Employee employee,HttpSession httpSession){
        //补全更新人信息
        Long empId = (Long) httpSession.getAttribute("employee");
        employee.setUpdateUser(empId);
        R update = ruiJiService.update(employee);
        return R.success(update);
    }

    @GetMapping("{id}")
    public R findById(@PathVariable("id") Long id){
        R<Employee> byId = ruiJiService.findById(id);
        return byId;
    }


}
